$(function () {
    var stu_data, total_page,
        cur_page = 1,
        is_filter = false;

    function init() {
        $.ajax({
            url: '/stu_list',
            dataType: 'json',
            success: function (resp) {
                stu_data = resp
                total_page = Math.ceil(stu_data.length / 10)
                render_stu_list()
                render_page()
                bind_event()
                render_charts()
            }
        })
    }

    init()

    // 渲染学生列表
    function render_stu_list() {
        var data = stu_data;
        // 是否过滤
        if (is_filter) {
            var key = $('.stu-list .order-item').val()
            var value = $('.stu-list .search-inp').val()
            data = stu_data.filter(function (item) {
                return String(item[key]).indexOf(value) != -1
            })
        }
        total_page = Math.ceil(data.length / 10)
        var html_str = data.slice((cur_page - 1) * 10, cur_page * 10).map(function (item) {
            return `<tr>
                <td>${item.sNo}</td>
                <td>${item.name}</td>
                <td>${item.sex}</td>
                <td>${item.email}</td>
                <td>${item.age}</td>
                <td>${item.phone}</td>
                <td>${item.address}</td>
                <td>
                    <button data-id="${item.sNo}" class="edit-btn">编辑</button>
                    <button data-id="${item.sNo}" class="del-btn">删除</button>
                </td>
            </tr>`
        }).join('')
        $('.stu-list tbody').html(html_str)
    }

    function bind_event() {
        // 菜单栏切换
        $('.nav-list dd').click(function () {
            var index = $(this).index() - 1
            $(this).addClass('active').siblings().removeClass('active')
            $('.content > div').eq(index).show().siblings().hide()
        })
        $('header ul li').click(function () {
            var index = $(this).index()
            $(this).addClass('active').siblings().removeClass('active')
            $('.content > div').eq(index).show().siblings().hide()
            $('header ul').slideUp()
        })

        // 菜单按钮
        $('header button').click(() => {
            $('header ul').slideToggle()
        })

        // 编辑按钮
        $('.stu-list table').on('click', '.edit-btn', function () {
            var form = $('.edit-form')[0]
            var tds = $(this).parents('tr').find('td')
            form.name.value = tds.eq(1).html()
            form.sex.value = tds.eq(2).html()
            form.email.value = tds.eq(3).html()
            form.age.value = tds.eq(4).html()
            form.phone.value = tds.eq(5).html()
            form.address.value = tds.eq(6).html()
            $('.mask .change-btn').data('id', tds.eq(0).html())
            // jquery.data 设置的 data 在 html 中看不到，但实际上已经设置成功了，必须用 jquery.data 查看
            // document.querySelector('.mask .change-btn').dataset.id = tds.eq(0).html()
            $('.mask').slideDown()
        })

        // 删除按钮
        $('.stu-list table').on('click', '.del-btn', function () {
            if (!confirm('确认删除')) return;
            var id = $(this).data('id');
            var self = this
            $.ajax({
                url: '/stu_del',
                type: 'post',
                dataType: 'json',
                data: { id },
                success: function (resp) {
                    if (resp.status == 'success') {
                        stu_data.forEach(function (item, index) {
                            if (item.sNo == id) {
                                stu_data.splice(index, 1)
                            }
                        })
                        $(self).parents('tr').remove()
                    }
                }
            })
        })

        // 修改按钮
        $('.mask .change-btn').click(function (e) {
            e.preventDefault()
            var params = $('.mask .edit-form').serialize();
            var id = $(this).data('id')
            $.ajax({
                url: '/stu_change',
                type: 'post',
                dataType: 'json',
                data: { params, id },
                success: function (resp) {
                    if (resp.status == 'success') {
                        for (var i = 0; i < stu_data.length; i++) {
                            if (stu_data[i].sNo == id) {
                                var params_obj = parse_params(params)
                                params_obj.sNo = id
                                stu_data[i] = params_obj
                                break
                            }
                        }
                        render_stu_list()
                        $('.cancel-btn').trigger('click')
                    }
                }
            })
        })

        // 取消按钮
        $('.cancel-btn').click(function (e) {
            e.preventDefault()
            $('.mask').slideUp()
        })

        // 提交按钮
        var tip_timer = null;
        $('.stu-add .submit-btn').click(function (e) {
            e.preventDefault()
            var form_obj = parse_params($('.add-form').serialize())
            var tip = check_params(form_obj)
            if (tip !== true) {
                $('.stu-add .tips').html(tip).show()
                clearTimeout(tip_timer)
                tip_timer = setTimeout(function () {
                    $('.stu-add .tips').hide()
                }, 2500)
            } else {
                $.ajax({
                    url: '/stu_add',
                    type: 'post',
                    data: {
                        name: form_obj.name,
                        age: form_obj.age,
                        sex: form_obj.sex,
                        phone: form_obj.phone,
                        email: form_obj.email,
                        address: form_obj.address,
                    },
                    dataType: 'json',
                    success: function (resp) {
                        if (resp.status === 'success') {
                            stu_data.push(resp.data)
                            total_page = Math.ceil(stu_data.length / 10)
                            cur_page = total_page
                            render_stu_list()
                            render_page()
                            $('.stu-add .reset-btn').triggerHandler('click')
                        }
                    }
                })
            }
        })

        // 重置按钮
        $('.stu-add .reset-btn').click(function (e) {
            e.preventDefault()
            var form = $('.add-form')[0]
            form.name.value = ''
            form.age.value = ''
            form.sex.value = '男'
            form.phone.value = ''
            form.email.value = ''
            form.address.value = ''
        })

        // 随机新增按钮
        $('.stu-list .add-random-btn').click(function () {
            $.ajax({
                url: '/stu_add_random',
                dataType: 'json',
                success: function (resp) {
                    if (resp.status == 'success') {
                        stu_data.push(resp.data)
                        total_page = Math.ceil(stu_data.length / 10)
                        cur_page = total_page
                        render_stu_list()
                        render_page()
                    }
                }
            })
        })

        // 搜索按钮
        $('.stu-list .search-btn').click(function () {
            var value = $('.stu-list .search-inp').val().trim()
            if (!value) return;
            is_filter = true
            cur_page = 1
            render_stu_list()
            render_page()
        })

        // 返回按钮
        $('.stu-list .back-btn').click(function () {
            $('.stu-list .search-inp').val('')
            is_filter = false
            cur_page = 1
            render_stu_list()
            render_page()
        })

        // 切换页数
        $('.stu-list .pagination').on('click', 'li', function () {
            var page_str = $(this).html()
            if (page_str == '&lt;')
                cur_page--
            else if (page_str == '&gt;')
                cur_page++
            else {
                cur_page = parseInt(page_str)
            }

            if (cur_page < 1)
                cur_page = 1
            else if (cur_page > total_page)
                cur_page = total_page
            render_stu_list()
            render_page()
        })

        // 表单验证
        function check_params(form_obj) {
            var is_valid = Object.values(form_obj).every(item => item.trim())
            if (!is_valid) return '请将表单填写完整'

            if (!/^\w+[\.\w+]?@\w+\.\w+$/.test(form_obj.email))
                return '邮箱填写有误'

            if (!/^\d+$/.test(form_obj.age))
                return '年龄填写有误'

            if (!/^1[3-9]\d{9}$/.test(form_obj.phone))
                return '手机号填写有误'

            return true
        }
    }

    // 分页函数
    function render_page() {
        var start = '<li>&lt;</li>',
            end = '<li>&gt;</li>',
            center = '';
        if (total_page <= 8) {
            for (var i = 1; i <= total_page; i++) {
                center += `<li class="${cur_page == i ? 'cur_page' : ''}">${i}</li>`
            }
        } else {
            if (cur_page <= 4) {
                for (var i = 1; i <= cur_page + 2; i++) {
                    center += `<li class="${cur_page == i ? 'cur_page' : ''}">${i}</li>`
                }
                center += `······<li>${total_page}</li>`
            } else if (cur_page > total_page - 4) {
                center += '<li>1</li>······'
                for (var i = cur_page - 2; i <= total_page; i++) {
                    center += `<li class="${cur_page == i ? 'cur_page' : ''}">${i}</li>`
                }
            } else {
                center += '<li>1</li>······';
                for (var i = cur_page - 2; i <= cur_page + 2; i++) {
                    center += `<li class="${cur_page == i ? 'cur_page' : ''}">${i}</li>`
                }
                center += `······<li>${total_page}</li>`
            }
        }
        $('.stu-list .pagination').html(start + center + end)
    }

    function render_charts() {
        const address_chart = echarts.init($('.stu-charts .address-chart').get(0)),
            sex_chart = echarts.init($('.stu-charts .sex-chart').get(0)),
            address_data = {},
            address_legend = [],
            address_series = [],
            sex_data = {},
            sex_legend = [],
            sex_series = [];

        stu_data.forEach(item => {
            const address = item.address.split(' ')[0]
            if (address_data[address]) {
                address_data[address]++
            } else {
                address_data[address] = 1
                address_legend.push(address)
            }
            if (sex_data[item.sex]) {
                sex_data[item.sex]++
            } else {
                sex_data[item.sex] = 1
                sex_legend.push(item.sex)
            }
        })

        for (const prop in address_data) {
            address_series.push({
                name: prop,
                value: address_data[prop]
            })
        }

        for (const prop in sex_data) {
            sex_series.push({
                name: prop,
                value: sex_data[prop]
            })
        }

        address_chart.setOption({
            title: {
                text:'渡一教育学生地区分布统计',
                subtext: '这是副标题',
                left: 'center'
            },
            legend: {   // 传奇，图例，说明
                data: address_legend,
                orient: 'vertical',     // 朝向，面对方向
                left: 'left'
            },
            tooltip: {}, // 提示框，使用默认
            series: {   // 系列
                name:'地区分布',
                type: 'pie',
                data: address_series,
                radius: ['45%', '60%'],
                center: ['65%', '50%'],
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowColor: '#333'
                    }
                },
            }
        })
        
        sex_chart.setOption({
            title: {
                text:'渡一教育学生性别分布统计',
                subtext: '这是副标题',
                left: 'center'
            },
            legend: {  
                data: sex_legend,
                orient: 'vertical',     
                left: 'left'
            },
            tooltip: {}, 
            series: {   
                name:'性别分布',
                type: 'pie',
                data: sex_series,
                // radius: ['50%', '60%'],
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowColor: '#008c8c'
                    }
                },
            },
        })
    }
})